//
//  TKStatusViewModel.swift
//  TKWBOne
//
//  Created by tiankun on 16/8/31.
//  Copyright © 2016年 1. All rights reserved.
//

import Foundation

//上拉刷新最大尝试次数
private let maxPullupTryTimes = 3
class TKStatusViewModel {
    lazy var statusList = [TKStatus]()
    private var pullupErrorTimes = 0
    func loadStatus(pullup: Bool, completion: (isSuccess: Bool, shouldRefresh: Bool)->()) {
        if pullup && pullupErrorTimes > maxPullupTryTimes {
            completion(isSuccess: true, shouldRefresh: false)
            return
        }
        let since_id = pullup ? 0 : (statusList.first?.id ?? 0)
        let max_id = !pullup ? 0 : (statusList.last?.id ?? 0)
        TKNetworkManager.shared.statusList(since_id: since_id, max_id: max_id) { (list, isSuccess) in
            guard let array = NSArray.yy_modelArray(with: TKStatus.self, json: list ?? []) as? [TKStatus] else {
                completion(isSuccess: isSuccess, shouldRefresh: false)
                return
            }
            print("刷新到\(array.count)条数据")
            if pullup {
                self.statusList += array
            } else {
                self.statusList = array + self.statusList
            }
            if pullup && array.count == 0 {
                self.pullupErrorTimes += 1
                completion(isSuccess: isSuccess, shouldRefresh: false)
            } else {
                completion(isSuccess: isSuccess, shouldRefresh: true)
            }
        }
    }
}
